const KEY_TYPE = '故障类型';
const KEY_PHENOMENON = '故障现象';
const KEY_REASON = '故障原因';

export const covertFieldsLabel = (arrayData) => {
  return arrayData.map((item) => {
    const steps = Object.keys(item)
    .filter((keyName) => ![KEY_TYPE, KEY_PHENOMENON, KEY_REASON].includes(keyName))
    .map((key) => item[key])

    return {
      type: item[KEY_TYPE],
      phenomenon: item[KEY_PHENOMENON],
      reason: item[KEY_REASON],
      steps,
    }
  })
}

export const flatData = (arrayData) => {
  const newArrayData = [];
  arrayData.forEach((item) => {
    const existTypes = newArrayData.filter((newItem) => newItem.value === item.type)
    if (existTypes.length > 0) {
      const existPhenomenon = existTypes[0].children.filter((newItem) => newItem.value === item.phenomenon)
      if (existPhenomenon.length > 0) {
        existPhenomenon[0].children.push({
          label: item.reason,
          value: item.reason,
          children: item.steps
        })
      } else {
        existTypes[0].children.push(
          {
            label: item.phenomenon,
            value: item.phenomenon,
            children: [
              {
                label: item.reason,
                value: item.reason,
                children: item.steps
              }
            ]
          }
        )
      }
    } else {
      newArrayData.push({
        label: item.type,
        value: item.type,
        children: [
          {
            label: item.phenomenon,
            value: item.phenomenon,
            children: [
              {
                label: item.reason,
                value: item.reason,
                children: item.steps
              }
            ]
          }
        ]
      })
    }
  })

  return newArrayData;
}
